import {getUserBySocketId} from '../service/message'
import {myEvent} from '../utils/common'
import {socketLogout} from '../service/socket'

const socketIo = require('socket.io')

module.exports = function(server) {
  const io = socketIo(server)
  // socket连接
  // 聊天服务
  const chat = io.of('/chat')
  // 主动推送消息
  myEvent.on('receive message', (message, toUser) => {
    chat.to(toUser.socketId).emit('receive message', message)
  })
  myEvent.on('unread count', (count, toUser) => {
    chat.to(toUser.socketId).emit('unread count', count)
  })

  chat.on('connection', (socket) => {
    socket.on('disconnect', async () => {
      const user = await getUserBySocketId(socket.id)
      if (!user) return
      await socketLogout(user._id)
      console.log(`${user.nickname} 已断开连接 ${new Date().toLocaleString()}`)
    })
  })
}
